﻿using System;
using System.Net;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace oop_5_server
{
    public class WebServer
    {
        private readonly HttpListener _listener = new HttpListener();
        private readonly Func<HttpListenerRequest, string> _responderMethod;

        public WebServer(Func<HttpListenerRequest, string> method)
        {
            _listener.Prefixes.Add("http://localhost:8080/");
            //_listener.Prefixes.Add("http://192.168.1.106:8080/");
            _listener.Start();

            _responderMethod = method;
        }

        public void Start()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Console.WriteLine("WebServer running...");
                try
                {
                    while (_listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem((c) =>
                        {
                            var ctx = c as HttpListenerContext;
                            try
                            {
                                string rstr = _responderMethod(ctx.Request);
                                byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                                Console.WriteLine(rstr);
                            }
                            catch (Exception e) {
                                Console.WriteLine(e); 
                            }
                            finally
                            {
                                ctx.Response.OutputStream.Close();
                            }
                        }, _listener.GetContext());
                    }
                }
                catch { }
            });
        }

        public void Stop()
        {
            _listener.Stop();
            _listener.Close();
        }

        public static string GetRequestPostData(HttpListenerRequest request)
        {
            if (!request.HasEntityBody)
            {
                return null;
            }

            using (System.IO.Stream body = request.InputStream)
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(body, request.ContentEncoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}
